#pragma once

#include <iostream>
#include <string>
#include <unordered_map>

#include "Log.hpp"
#include "Common.hpp"

using namespace LogModule;

const std::string sep = ":";

class Dict
{
private:
    void Load()
    {
        // 打开文件
        std::ifstream in(_path);
        if (!in.is_open())
        {
            LOG(FATAL, "file: %s open failed\n", _path);
            exit(FILE_OPEN);
        }

        // 读取每一行
        std::string line;
        while (std::getline(in, line))
        {
            LOG(DEBUG, "load %s success\n", line.c_str());
            if (line.empty()) // 空行
                continue;
            auto pos = line.find(sep);
            if (pos == std::string::npos) // 最后只有分隔符
                continue;
            std::string key = line.substr(0, pos);
            if (key.empty()) //       ：xxxx
                continue;
            std::string value = line.substr(pos + sep.size());
            if (value.empty()) // xxxxx:
                continue;

            _dict.insert(std::make_pair(key, value));
        }
        LOG(DEBUG, "load done\n");
        in.close();
    }

public:
    Dict(const std::string &path)
        : _path(path)
    {
        Load();
    }

    std::string Transform(std::string word)
    {
        if (word.empty())
            return "None";
        auto iter = _dict.find(word);
        return iter == _dict.end() ? "None" : iter->second;
    }

    ~Dict()
    {
    }

private:
    std::string _path;                                  // 文件的路径
    std::unordered_map<std::string, std::string> _dict; // 映射
};